﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Globalization;

namespace CoolERP_Common
{
    public sealed class DesHelper
    {
        public DesHelper()
        {
            //Key = GenerateKey();
        }

        /// <summary>
        /// 创建Key
        /// </summary>
        /// <returns></returns>
        public string GenerateKey()
        {
            DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
            return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
        }

        /// <summary>
        /// 对称加密解密的密钥
        /// </summary>
        public static string Key
        {
            get { return _key; }
            set { _key = value; }
        }
        private static string _key = "abcdefgh";

        /// <summary>
        /// 加密
        /// <summary>
        public static string Encrypt(string encryptString)
        {
            byte[] data = Encoding.UTF8.GetBytes(encryptString);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(Key);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(Key);
            ICryptoTransform desencrypt = DES.CreateEncryptor();
            byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
            return BitConverter.ToString(result);
        }

        /// <summary>
        /// 解密
        /// </summary>
        public static string Decrypt(string decryptString)
        {
            string[] sInput = decryptString.Split("-".ToCharArray());
            byte[] data = new byte[sInput.Length];
            for (int i = 0; i < sInput.Length; i++)
            {
                data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
            }
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(Key);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(Key);
            ICryptoTransform desencrypt = DES.CreateDecryptor();
            byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
            return Encoding.UTF8.GetString(result);

        }
    }
}
